<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Admin\SliderRequest;
use App\Models\Slider;
use App\Services\QiniuImageUploadService;
use Illuminate\Support\Facades\Storage;
use zgldh\QiniuStorage\QiniuStorage;
use App\Transformers\SliderTransformer;
use Illuminate\Http\Request;

class SliderController extends BaseController
{
    public $prefixPath = 'shopApi/'; // 子目录前缀

    /**
     * 轮播图列表
     */
    public function index(Request $request)
    {
        $sliders = Slider::orderBy('seq', 'desc')->paginate($request->size);
        return $this->response->paginator($sliders, new SliderTransformer());
    }

    /**
     * 添加轮播图
     */
    public function store(SliderRequest $request)
    {
        //查询最大的seq
        $max_seq = Slider::max('seq') ?? 0;
        $max_seq++;
        $request->offsetSet('seq', $max_seq);
        Slider::create($request->all());
        return $this->response->created();
    }

    /**
     * 轮播图详情
     */
    public function show(Slider $slider)
    {
        return $this->response->item($slider, new SliderTransformer());
    }

    /**
     * 更新轮播图
     */
    public function update(SliderRequest $request, Slider $slider)
    {
        $slider->update($request->all());
        return $this->response->noContent();
    }

    /**
     * 删除轮播图
     */
    public function destroy(Slider $slider, QiniuImageUploadService $imageUploadService)
    {
        //删除轮播图图片
        if ($slider->img) {
            //$imageUploadService->delete($slider->img);
            $disk = Storage::disk('qiniu');
            $imagePath = $this->prefixPath . $slider->img;
            // 删除单条文件
            $disk->delete($imagePath);
        }
        $slider->delete();
        return $this->response->noContent();
    }

    /**
     * 排序
     */
    public function seq(Request $request, Slider $slider)
    {
        $slider->seq = $request->input('seq', 1);
        $slider->save();
        return $this->response->noContent();
    }
}
